package com.zrrd.learn.framework.mybatis.mybatisinterface.service;

import com.zrrd.learn.framework.mybatis.mybatisinterface.entity.StudentEntity;
import com.zrrd.learn.framework.mybatis.mybatisinterface.mapper.StudentMapper;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * 业务处理
 * @author wrn
 * @version 1.0
 * @date 2023/9/4 10:17
 */

public class StudentService {

    private final String resource = "mybatisconfiguration.xml";

    /**
     * 封装一个方法 用来返回 sqlsession
     *
     * @return sqlsession
     */
    public SqlSession getSqlSession() {
        InputStream inputStream = null;
        try {
            //把mybatisconfiguration里面的信息读取到java里面
            inputStream = Resources.getResourceAsStream(resource);

            //建造者模式  [把xml里面的文本信息读取java并为大量的java类完成初始化赋値]
            SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
            SqlSessionFactory sqlSessionFactory = builder.build(inputStream);
            //把你想要处理的mapper存储到factory
            sqlSessionFactory.getConfiguration().addMapper(StudentMapper.class);

            SqlSession ss = sqlSessionFactory.openSession(true);
            return ss;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public StudentEntity findOne(String stu_name) {
        return getSqlSession().getMapper(StudentMapper.class).findOneByName(stu_name);
    }

    /**
     * 用来调用 mapper 里面的查询全部
     *
     * @return
     */
    public List<Map<String, Object>> showAll() {
        StudentMapper sm = getSqlSession().getMapper(StudentMapper.class);
        return sm.showAll();
    }

    /**
     * ui(。。。) uid（。。）
     * 练会它.... (。。。业务分析 coding)  (架构 20K 20W)
     *
     * @return
     */
    public List<StudentEntity> showAll1() {
        return getSqlSession().getMapper(StudentMapper.class).showAllWithEntity();
    }

    /**
     * 修改方法
     *
     * @param se    实体
     * @param oldId 原始id
     * @return
     */
    public int updateStu(StudentEntity se, int oldId) {
        StudentMapper studentMapper = getSqlSession().getMapper(StudentMapper.class);

        StudentEntity ones = studentMapper.findOneById(oldId);

        int sum = 0;

        if (Objects.nonNull(ones)) {
            sum = studentMapper.updateStudent(se, oldId);
        }

        return sum;
    }

}